import time
from threading import Thread, Semaphore, BoundedSemaphore
import sys
from common.utility import Utility

# 主函数
def main(initial_value: int = 5, use_semaphore: bool = True, is_blocking: bool = True,
         timeout: float | None = None, thread_count: int = 500, thread_sleep_time: float = 1) -> None:
    """
    主函数。测试线程及信号量。
    Args:
        initial_value (int):信号量的初始值。
        use_semaphore (bool):使用信号量还是有界信号量。True-信号量（Semaphore）；False-有界信号量（BoundedSemaphore）。
        is_blocking (bool):在请求信号量时是否阻塞。True-阻塞；False-不阻塞。
        timeout (float):超时时间（秒）。
        thread_count (int):子线程的数量。
        thread_sleep_time (float):子线程休眠的时间（秒），用于模拟繁重任务的执行时间。

    Returns:
        无。
    """
    global semaphore
    Utility.print_info('entered.')
    semaphore = Semaphore(initial_value) if use_semaphore else BoundedSemaphore(initial_value)
    threads: list[Thread] = []
    for i in range(thread_count):
        threads.append(start_thread(is_blocking, timeout, thread_sleep_time))
    for thread in threads:
        thread.join()
    Utility.print_info('exited.')

# 创建线程
def start_thread(is_blocking: bool, timeout: float | None, sleep_time: float) -> Thread:
    thread: Thread = Thread(target=task, args=(is_blocking, timeout, sleep_time))
    thread.start()
    return thread

# 任务
def task(is_blocking: bool, timeout: float | None, sleep_time: float) -> None:
    global semaphore
    Utility.print_info('entered.')
    acquire_result: bool = False
    try:
        acquire_result = semaphore.acquire(is_blocking, timeout)
        Utility.print_info(f'acquire {'success, doing some works' if acquire_result else 'failed'}.')
        if acquire_result:
            time.sleep(sleep_time)
    finally:
        if acquire_result:
            semaphore.release()
    Utility.print_info('exited.')

print(f'is gil enabled: {sys._is_gil_enabled()}')
print(f'python version: {sys.version}')
semaphore: Semaphore | BoundedSemaphore
main(3, True, True, 0.5, 10, 0.3)